<!-- subpkg_medicine/payment/index.vue -->
<script lang="ts" setup>
import { addressListApi, preOrderApi } from '@/apis/order'
import type { Address, OrderPre } from '@/types/order'
import { ref } from 'vue'
import CustomPayment from '@/components/custom-payment/custom-payment.vue'
import { createOrderApi } from '@/apis/order'
import { orderPayApi } from '@/apis/consult'
import MedicineList from '@/components/medicine-list/medicine-list.vue'

// 1. 获取地址
const address = ref<Address>()
const getAddressList = async () => {
  const addressList = await addressListApi()
  const defaultAddress = addressList.find((item) => item.isDefault)
  if (defaultAddress) {
    address.value = defaultAddress
  } else {
    address.value = addressList[0]
  }
}
getAddressList()

// 2. 获取药品订单预支付信息
const props = defineProps<{ id: string }>()
// 预付订单信息
const preOrderInfo = ref({} as OrderPre)
// 药品预付订单
const getPreOrder = async () => {
  if (!props.id) return
  // 预付订单接口
  const data = await preOrderApi(props.id)
  // 渲染预付订单信息
  preOrderInfo.value = data
  console.log(preOrderInfo.value)
}
getPreOrder()

// 3. 生成订单
const orderId = ref('')
const customPaymentRef = ref()
// 3.1 打开支付抽屉
const onPaymentButtonClick = async () => {
  if (orderId.value === '') {
    if (!props.id) return
    if (!address.value) return
    const res = await createOrderApi(props.id, address.value.id)
    orderId.value = res.id
  }

  customPaymentRef.value.open()
}

// 3.2 关闭支付渠道弹层
const onPaymentClose = () => {
  customPaymentRef.value.close()
}

// 3.3 支付渠道确认支付
const onPaymentConfirm = async (index: number) => {
  try {
    if (index === undefined) return uni.showToast({ title: '请选择支付方式', icon: 'none' })
    if (index === 0) return uni.showToast({ title: '暂不支持微信支付', icon: 'none' })
    // 调用后端提供的支付接口
    uni.showLoading({ title: '正在调整支付' })
    const data = await orderPayApi({
      orderId: orderId.value,
      paymentMethod: index.toString(),
      payCallback: 'http://localhost:5173/#/subpkg_medicine/pay_result/index',
    })
    // 支付宝支付页面
    window.location.href = data.payUrl
  } catch (error) {
    console.log(error, 666)
  }
}
</script>

<template>
  <scroll-page background-color="#f6f6f6">
    <view class="medicine-page">
      <!-- 头部 -->
      <view class="page-header">
        <view class="order-shippment">
          <view class="region">
            <uni-icons size="16" color="#FF7702" type="location-filled" />
            {{ address?.city }}{{ address?.county }}
          </view>
          <view class="detail">{{ address?.addressDetail }}</view>
          <view class="receiver"
            >{{ address?.receiver }}
            {{ address?.mobile?.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') }}</view
          >
        </view>
      </view>

      <view class="order-shop">
        优医药房
        <text class="alt">优医质保 假一赔十</text>
      </view>
      <!-- 药品列表 -->
      <MedicineList :medicines="preOrderInfo.medicines" />

      <!-- 订单信息 -->
      <view class="order-info">
        <uni-list :border="false">
          <uni-list-item title="药品金额" :right-text="'¥' + preOrderInfo.payment" />
          <uni-list-item title="运费" :right-text="'¥' + preOrderInfo.expressFee" />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="'-¥' + preOrderInfo.couponDeduction"
          />
          <uni-list-item title="实付款" :right-text="'¥' + preOrderInfo.actualPayment" />
        </uni-list>
      </view>

      <!-- 底部 -->
      <view class="toolbar">
        <view class="total-amount">
          需付款: <text class="number">¥{{ preOrderInfo.actualPayment }}</text>
        </view>
        <view class="buttons">
          <button class="uni-button" @click="onPaymentButtonClick">立即支付</button>
        </view>
      </view>
    </view>

    <CustomPayment
      ref="customPaymentRef"
      :order-id="orderId"
      :amount="preOrderInfo.actualPayment"
      @close="onPaymentClose"
      @confirm="onPaymentConfirm"
    />
  </scroll-page>
</template>

<style lang="scss">
@import './index.scss';
</style>